package com.medical.Service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.medical.DTO.EmployeeDTO;
import com.medical.DTO.EmployeePageDTO;
import com.medical.DTO.LoginDTO;
import com.medical.Mapper.EmployeeMapper;
import com.medical.Mapper.UserMapper;
import com.medical.Service.EmployeeService;
import com.medical.VO.EmployeeVO;
import com.medical.VO.LoginVO;
import com.medical.result.PageResult;
import com.medical.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    /*
     * 登录
     */
    @Override
    public LoginVO login(LoginDTO loginDTO) {
        try {
            System.out.println("LoginService: 尝试登录用户 " + loginDTO.getUsername());
            LoginVO loginVO = userMapper.getByUsernameAndPassword(loginDTO);

            if (loginVO == null) {
                System.out.println("LoginService: 用户名或密码错误");
                return null;
            }

            System.out.println("LoginService: 用户验证成功");

            Map<String, Object> claims = new HashMap<>();
            claims.put("username", loginVO.getUsername());
            if (loginVO.getName() != null) {
                claims.put("name", loginVO.getName());
            }

            String token = JwtUtil.generateToken(claims);
            loginVO.setToken(token);
            System.out.println("LoginService: Token生成成功");

            return loginVO;
        } catch (Exception e) {
            System.err.println("LoginService异常: " + e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }


    /*
     * 新增员工
     */
    @Override
    public void addEmployee(EmployeeDTO employee) {
        employee.setCreatedDate(LocalDateTime.now());
        employeeMapper.insert(employee);
    }


    /*
     * 删除员工
     */
    @Override
    public void deleteEmployee(List<Integer> ids) {
        employeeMapper.delete(ids);
    }

    /*
     * 修改员工
     */
    @Override
    public void updateEmployee(EmployeeDTO employee) {
        employeeMapper.update(employee);
    }


    /**
     * 获取员工列表
     */
    @Override
    public PageResult page(EmployeePageDTO employeePage) {
        PageHelper.startPage(employeePage.getPage(), employeePage.getPageSize());
        Page<EmployeeVO> page = (Page<EmployeeVO>) employeeMapper.getEmployeeList(employeePage);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return pageResult;
    }


}
